package com.hjm.project.salesman.salesman.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.DateUtils;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.framework.shiro.service.PasswordService;
import com.hjm.project.accounts.accounts.domain.Accounts;
import com.hjm.project.accounts.accounts.mapper.AccountsMapper;
import com.hjm.project.agentDateCen.agentDateCen.domain.AgentDateCen;
import com.hjm.project.agentDateCen.agentDateCen.mapper.AgentDateCenMapper;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfo;
import com.hjm.project.agentInfo.agentInfo.mapper.AgentInfoMapper;
import com.hjm.project.agentInfo.agentInfo.utils.Utils;
import com.hjm.project.agentInfo.point.domain.TaxPoint;
import com.hjm.project.agentInfo.point.mapper.TaxPointMapper;
import com.hjm.project.agentInfo.total.domain.AgentTotal;
import com.hjm.project.agentInfo.total.mapper.AgentTotalMapper;
import com.hjm.project.cardBag.domain.CardBag;
import com.hjm.project.cardBag.mapper.CardBagMapper;
import com.hjm.project.gears_info.domain.GearsInfo;
import com.hjm.project.gears_info.mapper.GearsInfoMapper;
import com.hjm.project.merchantInfo.merRecord.mapper.MerRecordMapper;
import com.hjm.project.riskControl.riskmerblack.domain.Riskmerblack;
import com.hjm.project.riskControl.riskmerblack.mapper.RiskmerblackMapper;
import com.hjm.project.system.user.domain.User;
import com.hjm.project.system.user.domain.UserRole;
import com.hjm.project.system.user.mapper.UserMapper;
import com.hjm.project.system.user.mapper.UserRoleMapper;
import com.hjm.project.terminal.agentTargetInfo.agentTargetInfo.mapper.AgentTargetInfoMapper;
import com.yxhd.encrypt.EncryptUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hjm.project.salesman.salesman.mapper.SalesmanMapper;
import com.hjm.project.salesman.salesman.domain.Salesman;
import com.hjm.project.salesman.salesman.service.ISalesmanService;
import com.hjm.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 业务员Service业务层处理
 * 
 * @author admin
 * @date 2020-11-20
 */
@Service
public class SalesmanServiceImpl implements ISalesmanService 
{
    @Autowired
    private SalesmanMapper salesmanMapper;
    @Resource
    private UserMapper userMapper;                  //用户
    @Resource
    private AgentTotalMapper totalMapper;           //统计代理
    @Resource
    private AgentDateCenMapper agentDateCenMapper;  //代理初始化数据
    @Resource
    private TaxPointMapper taxPointMapper;          //税点
    @Resource
    private AgentTargetInfoMapper agentTargetInfoMapper;    //档位分配记录
    @Resource
    private CardBagMapper cardBagMapper;            //卡包数据表
    @Resource
    private AgentTotalMapper agentTotalMapper;
    @Resource
    private MerRecordMapper merRecordMapper;
    @Resource
    private RiskmerblackMapper riskmerblackMapper;
    @Resource
    private AgentInfoMapper agentInfoMapper;        //代理商信息
    @Resource
    private GearsInfoMapper gearsInfoMapper;        //档位
    @Resource
    private AccountsMapper accountsMapper;          //结算账户
    @Resource
    private PasswordService passwordService;        //密码服务(加密修改密码)
    @Resource
    private UserRoleMapper userRoleMapper;          //用户角色分配

    /**
     * 查询业务员
     * 
     * @param smNum 业务员ID
     * @return 业务员
     */
    @Override
    public Salesman selectSalesmanById(Long smNum)
    {
        return salesmanMapper.selectSalesmanById(smNum);
    }

    /**
     * 查询业务员列表
     * 
     * @param salesman 业务员
     * @return 业务员
     */
    @Override
    public List<Salesman> selectSalesmanList(Salesman salesman)
    {
        return salesmanMapper.selectSalesmanList(salesman);
    }

    /**
     * 新增业务员
     * 
     * @param salesman 业务员
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSalesman(Salesman salesman) throws Exception {
        Salesman ss = new Salesman();
        ss.setSmPhone(salesman.getSmPhone());
        List<Salesman> salesmen = salesmanMapper.selectSalesmanList(ss);
        if (CollectionUtils.isNotEmpty(salesmen)) {
            throw new BusinessException("业务员手机号已存在");
        }
        //生成一个服务商编号
        Integer agentNum = agentInfoMapper.getAgentNum();
        salesman.setSmAddtime(DateUtils.getTime());
        salesman.setSaleAgentNum(agentNum.toString());
        int result = salesmanMapper.insertSalesman(salesman);
        AgentInfo agent = new AgentInfo();
        agent.setSaleType("1");
        agent.setSaleAgentNum(agentNum.toString());
        agent.setLinkPhone(salesman.getSmPhone());
        agent.setCommissary(salesman.getSmName());
        //服务商信息
        agent.setBelongAgent(Long.parseLong("0"));
        agent.setAddName(ShiroUtils.getSysUser().getObjNo() + "-" + ShiroUtils.getSysUser().getLoginName());
        agent.setSignSale(salesman.getSmNum());
        agent.setMaintain(salesman.getSmNum());
        agent.setAgentNature(Long.parseLong("0"));
        agent.setIdentityNum(salesman.getScreenIdnum());
        //法人的姓名和身份证号码
        //TODO 服务商管理 >> 服务商信息 >>二要素认证 法人的姓名和身份证号码（要素）
        Map map = new HashMap();
        map.put("ScreenName", agent.getCommissary());
        map.put("Idnumber", agent.getIdentityNum());
       /* Map map1 = EssentialFactors.twoElements(map);
        if ("1".equals(map1.get("status").toString())) {
            throw new BusinessException("法人二要素验证失败");
        }*/
        String idCard = agent.getIdentityNum();
        agent.setLocaldate(Utils.formateDate(0));
        agent.setLocaltime(Utils.formateDate(3));
        agent.setProfitStatus(Long.valueOf("0"));
        agent.setProfitType(Long.valueOf("1"));
        agent.setAgentStatus("0");
        agent.setShowIdentitynum(agent.getIdentityNum().substring(0, 10) + "****" + agent.getIdentityNum().substring(14));
        agent.setIdentityNum(EncryptUtils.getEncrypt(agent.getIdentityNum()));
        agent.setStatus("1");
        int count = userMapper.checkLoginNameUnique(agent.getLinkPhone());
        if (count > 0) {
            throw new BusinessException("当前手机号已注册,请更换手机号");
        }

        Riskmerblack riskmerblack = new Riskmerblack();
        riskmerblack.setType("2");
        riskmerblack.setTypeVal(idCard);
        List<Riskmerblack> riskmerblacks = riskmerblackMapper.selectRiskmerblackList(riskmerblack);
        if (CollectionUtils.isEmpty(riskmerblacks)) {
            //验证通过后查看当前注册人是否注册过
            AgentInfo agentInfo = new AgentInfo();
            agentInfo.setIdentityNum(agent.getIdentityNum());
            List<AgentInfo> agentInfos = agentInfoMapper.selectAgentInfoList(agentInfo);
            if (CollectionUtils.isNotEmpty(agentInfos) && !agentInfos.get(0).getAgentStatus().equals("5")) {
                throw new BusinessException("法人信息已注册,请更换法人信息");
            }
        }

        agent.setAgentNum(agentNum.toString());
        agent.setBeautiful(agentNum.toString());
        agent.setAgentName(salesman.getSmName());
        agent.setBeautifulName(salesman.getSmName());
        //默认最低档位的分润标准
        GearsInfo gearsInfo = new GearsInfo();
        gearsInfo.setIsMin("0");
        GearsInfo gearsInfo1 = gearsInfoMapper.selectGearsInfoList(gearsInfo).get(0);
        agent.setGrade(gearsInfo1.getGrade());
        agent.setSupportLevel("V1");
        agent.setSupportDate(DateUtils.getDate());
        //添加服务商
        int i = agentInfoMapper.insertAgentInfo(agent);
        //账户信息
        Accounts accounts = new Accounts();
        accounts.setNature(2);
        accounts.setScreenNum(salesman.getScreenNum());
        accounts.setResphone(salesman.getSmPhone());
        accounts.setScreenIdnum(salesman.getScreenIdnum());
        accounts.setBankAddress("1100,1100,1132");
        accounts.setSeqId(agentNum.toString());
        accounts.setCreatedate(new Date());
        accounts.setCreateman(ShiroUtils.getSysUser().getLoginName());
        accounts.setCreateBy(ShiroUtils.getSysUser().getLoginName());
        accounts.setDaMarker(1);
        //结算卡加*
        String screenNum = Utils.hiddenCard(accounts.getScreenNum());
        accounts.setShowScreennum(screenNum);
        //结算卡加密
        accounts.setScreenNum(EncryptUtils.getEncrypt(accounts.getScreenNum()));
        //手机号加*
        String phone = accounts.getResphone();
        accounts.setShowResphone(phone.substring(0, 3) + "****" + phone.substring(8, 11));
        //手机号加密
        accounts.setResphone(EncryptUtils.getEncrypt(accounts.getResphone()));
        accounts.setAreaName("天津市,天津市,南开区");
        //查看当前账户是对公还是对私类型
        //对公没有结算人身份照号
        int nature = accounts.getNature();
        if (nature == 2) {//对私
            String screenIdnum = accounts.getScreenIdnum();
            accounts.setScreenIdnum(EncryptUtils.getEncrypt(screenIdnum));
            accounts.setShowScreenidnum(screenIdnum.substring(0, 10) + "****" + screenIdnum.substring(14));
        } else if (nature == 1) {//对公
            accounts.setScreenIdnum("");
            accounts.setShowScreenidnum("");
        }
        //添加服务商账户
        int i2 = accountsMapper.insertAccounts(accounts);
        if (i >= 1 && i2 >= 1) {
            result = 1;
        }
        //结算卡数据同步卡包表一份
        CardBag cardBag = new CardBag();
        cardBag.setMerno(accounts.getSeqId());
        cardBag.setLocaldate(DateUtils.getDate());
        cardBag.setAdddate(DateUtils.getOnlyTime());
        cardBag.setScreenName(agent.getCommissary());
        cardBag.setScreenNum(accounts.getShowScreennum());
        cardBag.setScreenNumDense(accounts.getScreenNum());
        cardBag.setiCard(1);
        cardBag.setIdnumber(accounts.getShowScreenidnum());
        cardBag.setIsdefault(0);
        cardBag.setBankName(accounts.getBankName());
        cardBag.setBankHeadname(accounts.getBankHeadname());
        cardBag.setResphone(accounts.getShowResphone());
        cardBag.setResphoneDense(accounts.getResphone());
        cardBag.setBankNum(accounts.getBankNum());
        cardBag.setBottomPic("grey");
        cardBag.setPicno("000");
        cardBag.setBankAddress(accounts.getBankAddress());
        cardBag.setAreaName(accounts.getAreaName());
        cardBag.setCardType(1);
        int i3 = cardBagMapper.insertCardBag(cardBag);
        if (i3 <= 0) {
            throw new BusinessException("添加卡包数据失败");
        }
        //添加一个用户
        User user = new User();
        user.randomSalt();
        user.setLoginName(agent.getLinkPhone());
        user.setPassword(passwordService.encryptPassword(agent.getLinkPhone(), "00000000", user.getSalt()));
        user.setStatus("0");
        user.setDelFlag("0");
        user.setBelong(Long.parseLong("0"));
        user.setObjNo(String.valueOf(agentNum));
        user.setCreateTime(DateUtils.getNowDate());
        user.setSex("1");
        user.setCreateBy(ShiroUtils.getSysUser().getLoginName());
        user.setUserName(agent.getLinkPhone());
        user.setUserType("02");
        user.setDeptId(Long.parseLong("108"));
        int i1 = userMapper.insertUser(user);
        if (i1 <= 0) {
            throw new BusinessException("添加登录账户失败");
        }
        //默认添加为普通用户 需提升管理员联系运维人员
        UserRole userRole = new UserRole();
        userRole.setRoleId(Long.parseLong("927"));
        userRole.setUserId(user.getUserId());
        userRoleMapper.deleteUserRoleInfo(userRole);
        userRoleMapper.insertUserRole(userRole);

        //添加一条统计记录
        AgentTotal agentTotal = new AgentTotal();
        agentTotal.setAgentNum(agentNum.toString());
        agentTotal.setBelongAgent(ShiroUtils.getSysUser().getObjNo());
        totalMapper.insertAgentTotal(agentTotal);

        TaxPoint t = new TaxPoint();
        t.setAgentNum(agentNum.toString());
        t.setAddMan(ShiroUtils.getSysUser().getLoginName());

        t.setTaxPoint("0.08");
        t.setType(Long.valueOf("0"));
        taxPointMapper.insertTaxPoint(t);
        t.setTaxPoint("0.08");
        t.setType(Long.valueOf("4"));
        taxPointMapper.insertTaxPoint(t);

        TaxPoint tp = new TaxPoint();
        tp.setAgentNum(agentNum.toString());
        tp.setAddMan(ShiroUtils.getSysUser().getLoginName());

        tp.setTaxPoint("0.08");
        tp.setType(Long.valueOf("2"));
        taxPointMapper.insertTaxPoint(tp);
        tp.setTaxPoint("0.08");
        tp.setType(Long.valueOf("3"));
        taxPointMapper.insertTaxPoint(tp);

        //添加服务商的统计记录初始化数据(日 周  月)
        for (i = 1; i <= 3; i++) {
            AgentDateCen dateCen = new AgentDateCen();
            dateCen.setType(Long.parseLong(i + ""));
            //类型 1日统计 2月统计 3周统计
            //日统计 2020-11-23 月统计 2020-11，日月统计有值，周统计无值
            if (i == 1) {
                dateCen.setBelongDate(DateUtils.getDate());
            } else if (i == 2) {
                dateCen.setBelongDate(DateUtils.getDateYYYY_MM());
            } else if (i == 3) {
                Map<String, String> weekDate = DateUtils.getWeekDate();
                dateCen.setStartBelongDate(weekDate.get("startDate"));
                dateCen.setEndBelongDate(weekDate.get("endDate"));
            }
            dateCen.setAgentNum(Long.parseLong(agentNum.toString()));
            agentDateCenMapper.insertAgentDateCen(dateCen);
        }
        return result;
    }

    /**
     * 修改业务员
     * 
     * @param salesman 业务员
     * @return 结果
     */
    @Override
    public int updateSalesman(Salesman salesman) throws Exception {
        Salesman sa = salesmanMapper.selectSalesmanById(Long.parseLong(salesman.getSmNum()));
        String screenNum = salesman.getScreenNum();

        //结算卡脱敏
        String cardNum = Utils.hiddenCard(screenNum);
        //结算卡加密
        String cardNumD = EncryptUtils.getEncrypt(screenNum);

        //身份证号脱敏
        String idCard = salesman.getScreenIdnum().substring(0, 10) + "****" + salesman.getScreenIdnum().substring(14);
        //身份证号加密
        String idCardD = EncryptUtils.getEncrypt(salesman.getScreenIdnum());

        Accounts ac = new Accounts();
        ac.setSeqId(sa.getSaleAgentNum());
        ac.setScreenNum(cardNumD);
        ac.setShowScreennum(cardNum);
        ac.setScreenIdnum(idCardD);
        ac.setShowScreenidnum(idCard);
        accountsMapper.updateAccounts(ac);

        CardBag cardBag = new CardBag();
        cardBag.setMerno(sa.getSaleAgentNum());
        cardBag.setScreenNum(cardNum);
        cardBag.setScreenNumDense(cardNumD);
        cardBag.setIdnumber(idCard);
        cardBagMapper.updateCardBagScreenNum(cardBag);
        return salesmanMapper.updateSalesman(salesman);
    }

    /**
     * 删除业务员对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSalesmanByIds(String ids)
    {
        return salesmanMapper.deleteSalesmanByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除业务员信息
     * 
     * @param smNum 业务员ID
     * @return 结果
     */
    @Override
    public int deleteSalesmanById(Long smNum)
    {
        return salesmanMapper.deleteSalesmanById(smNum);
    }
}
